package alo.p5;
//基于简单循环数组实现队列
public class ArrayQueue {
    private int front;
    private int rear;
    private int capacity;
    private int[] array;
    private ArrayQueue(int size){
        capacity=size;
        front=-1;
        rear=-1;
        array=new int[size];
    }
    private static ArrayQueue createQueue(int size){
        return new ArrayQueue(size);
    }
    public boolean isEmpty(){
        return (front==-1);
    }
    public boolean isFull(){
        return (rear+1)%capacity==front;
    }
    public int getQueueSize(){
        return (capacity-front+rear+1)%capacity;
    }
    public void enQueue(int data) throws QueueOverflowException {
        if (isFull()){
            throw new QueueOverflowException("Queue Overfloe");
        }else {
            rear=(rear+1)%capacity;
            array[rear]=data;
            //如果栈还未添加过元素
            if (front==-1){
                front=rear;
            }
        }
    }
    public int deQueue() throws EmptyQueueException {
        int data= Integer.parseInt(null);
        if (isEmpty()){
            throw new EmptyQueueException("Queue Empty");
        }else {
            data= array[front];
            //如果只有一个元素
            if (front==rear){
                front=rear=-1;
            }else {
                front=(front+1)%capacity;
            }
        }
        return data;
    }

    private class QueueOverflowException extends Throwable {
        public QueueOverflowException(String queue_overfloe) {
            System.out.println(queue_overfloe);
        }

        @Override
        public void printStackTrace() {
            System.out.println("Queue Overfloe");
        }
    }

    private class EmptyQueueException extends Throwable {
        public EmptyQueueException(String queue_empty) {
            System.out.println(queue_empty);
        }

        @Override
        public void printStackTrace() {
            System.out.println("Queue Empty");
        }
    }
}
